package com.gin.kotlin.no_gay_alliance.base

import android.text.Editable
import android.text.TextWatcher
import android.widget.EditText

class IntRangeTextWatcher(
    private val editText: EditText,
    private val min: Int? = null,
    private val max: Int? = null,
) : TextWatcher {
    /**
     * 修改前的值
     */
    private var valueBefore: String? = null

    /**
     * 修改前保存修改前的值
     * @param s CharSequence
     * @param start Int
     * @param count Int
     * @param after Int
     */
    override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
        valueBefore = s.toString()
    }

    /**
     * 修改时检查输入值是否合法
     */
    override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
        if (s.isNullOrEmpty()) {
            return
        }
        val valueAfter = s.toString().toInt()

        if (min != null && valueAfter < min) {
            editText.setText(min.toString())
            editText.setSelection(editText.text.length, editText.text.length)
        }

        if (max != null && valueAfter > max) {
            editText.setText(max.toString())
            editText.setSelection(editText.text.length, editText.text.length)
        }
    }

    override fun afterTextChanged(s: Editable?) {
    }
}